<?php
namespace app\admin\controller;

use think\facade\Db;

class Log extends \app\BaseController
{
    /**
     * 操作日志列表
     */
    public function index()
    {
        // 确保session启动
        if (!session_id()) {
            session_start();
        }
        
        // 简单的登录检查
        if (!isset($_SESSION['admin_user'])) {
            return redirect('/admin/login');
        }
        
        // 获取查询参数
        $action = $this->request->param('action', '');
        $admin_name = $this->request->param('admin_name', '');
        $date_start = $this->request->param('date_start', '');
        $date_end = $this->request->param('date_end', '');
        $page = $this->request->param('page', 1);
        $limit = 20;
        
        // 构建查询条件
        $where = [];
        if (!empty($action)) {
            $where[] = ['action', '=', $action];
        }
        if (!empty($admin_name)) {
            $where[] = ['admin_name', 'like', '%' . $admin_name . '%'];
        }
        if (!empty($date_start)) {
            $where[] = ['create_time', '>=', strtotime($date_start)];
        }
        if (!empty($date_end)) {
            $where[] = ['create_time', '<=', strtotime($date_end . ' 23:59:59')];
        }
        
        try {
            // 确保日志表存在
            $this->createLogTableIfNotExists();
            
            // 获取日志列表
            $logs = Db::name('admin_log')
                     ->where($where)
                     ->order('create_time', 'desc')
                     ->paginate([
                         'list_rows' => $limit,
                         'page' => $page
                     ]);
            
            // 获取操作类型统计
            $actionStats = Db::name('admin_log')
                            ->field('action, count(*) as count')
                            ->group('action')
                            ->select()
                            ->toArray();
            
        } catch (\Exception $e) {
            $logs = [];
            $actionStats = [];
        }
        
        // 准备视图数据
        $data = [
            'title' => '操作日志',
            'current_menu' => 'log',
            'logs' => $logs,
            'action_stats' => $actionStats,
            'action' => $action,
            'admin_name' => $admin_name,
            'date_start' => $date_start,
            'date_end' => $date_end,
            'admin_user' => $_SESSION['admin_user']
        ];
        
        return view('log/index', $data);
    }
    
    /**
     * 日志详情
     */
    public function detail()
    {
        // 确保session启动
        if (!session_id()) {
            session_start();
        }
        
        // 简单的登录检查
        if (!isset($_SESSION['admin_user'])) {
            return redirect('/admin/login');
        }
        
        $id = $this->request->param('id');
        
        try {
            $log = Db::name('admin_log')->find($id);
            if (!$log) {
                return redirect('/admin/log')->with('error', '日志不存在');
            }
            
            // 获取相关操作记录（同一目标ID的其他操作）
            $relatedLogs = [];
            if (!empty($log['target_id'])) {
                $relatedLogs = Db::name('admin_log')
                                ->where('target_id', $log['target_id'])
                                ->where('id', '<>', $id)
                                ->order('create_time', 'desc')
                                ->limit(10)
                                ->select()
                                ->toArray();
            }
            
        } catch (\Exception $e) {
            return redirect('/admin/log')->with('error', '查询失败');
        }
        
        // 准备视图数据
        $data = [
            'title' => '日志详情',
            'current_menu' => 'log',
            'log' => $log,
            'related_logs' => $relatedLogs,
            'admin_user' => $_SESSION['admin_user']
        ];
        
        return view('log/detail', $data);
    }
    
    /**
     * 获取操作类型的中文名称
     */
    public static function getActionText($action)
    {
        $actionMap = [
            'login' => '管理员登录',
            'add_admin' => '添加管理员',
            'edit_admin' => '编辑管理员',
            'delete_admin' => '删除管理员',
            'change_admin_status' => '修改管理员状态',
            'approve_merchant' => '审核通过商户',
            'reject_merchant' => '审核拒绝商户',
            'delete_merchant' => '删除商户',
            'clear_log' => '清理日志',
        ];
        
        return $actionMap[$action] ?? $action;
    }
    
    /**
     * 获取操作类型的CSS类名
     */
    public static function getActionClass($action)
    {
        if (strpos($action, 'login') !== false) return 'action-login';
        if (strpos($action, 'add') !== false) return 'action-add';
        if (strpos($action, 'edit') !== false) return 'action-edit';
        if (strpos($action, 'delete') !== false) return 'action-delete';
        if (strpos($action, 'status') !== false) return 'action-status';
        if (strpos($action, 'approve') !== false) return 'action-approve';
        if (strpos($action, 'reject') !== false) return 'action-reject';
        if (strpos($action, 'clear') !== false) return 'action-clear';
        
        return 'action-default';
    }
    
    /**
     * 清理日志
     */
    public function clear()
    {
        // 确保session启动
        if (!session_id()) {
            session_start();
        }
        
        // 简单的登录检查
        if (!isset($_SESSION['admin_user'])) {
            return json(['code' => 0, 'msg' => '请先登录']);
        }
        
        $days = $this->request->post('days', 30);
        
        try {
            $cutoffTime = time() - ($days * 24 * 3600);
            $deletedCount = Db::name('admin_log')
                             ->where('create_time', '<', $cutoffTime)
                             ->delete();
            
            // 记录清理操作
            $adminUser = $_SESSION['admin_user'];
            Db::name('admin_log')->insert([
                'admin_id' => $adminUser['id'],
                'admin_name' => $adminUser['username'],
                'action' => 'clear_log',
                'description' => "清理了{$days}天前的日志，共{$deletedCount}条",
                'target_id' => 0,
                'ip' => $this->request->ip(),
                'user_agent' => $this->request->header('User-Agent'),
                'create_time' => time()
            ]);
            
            return json(['code' => 1, 'msg' => "成功清理{$deletedCount}条日志"]);
            
        } catch (\Exception $e) {
            return json(['code' => 0, 'msg' => '清理失败：' . $e->getMessage()]);
        }
    }
    
    /**
     * 创建日志表（如果不存在）
     */
    private function createLogTableIfNotExists()
    {
        try {
            $sql = "CREATE TABLE IF NOT EXISTS `admin_log` (
                `id` int(11) NOT NULL AUTO_INCREMENT,
                `admin_id` int(11) NOT NULL DEFAULT '0' COMMENT '管理员ID',
                `admin_name` varchar(50) NOT NULL DEFAULT '' COMMENT '管理员用户名',
                `action` varchar(50) NOT NULL DEFAULT '' COMMENT '操作类型',
                `description` text COMMENT '操作描述',
                `target_id` int(11) NOT NULL DEFAULT '0' COMMENT '目标ID',
                `ip` varchar(50) NOT NULL DEFAULT '' COMMENT 'IP地址',
                `user_agent` text COMMENT '用户代理',
                `create_time` int(11) NOT NULL DEFAULT '0' COMMENT '创建时间',
                PRIMARY KEY (`id`),
                KEY `admin_id` (`admin_id`),
                KEY `action` (`action`),
                KEY `create_time` (`create_time`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='管理员操作日志表';";
            
            Db::execute($sql);
        } catch (\Exception $e) {
            // 表创建失败不影响主要功能
        }
    }
}
